<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Web Socket Demo</title>
<script type="text/javascript" src="js/jquery-1.8.0.min.js"></script>
<script type="text/javascript"> 
		var ws = null; 

		function startServer() {
			// 设定WebSocket,注意协议是ws，请求是指向对应的WebSocketServlet的
			var uid = document.getElementById('uid').value;
			var cid = document.getElementById('cid').value;
			var url = "ws://localhost:8080/chat.ws?uid="+uid+"&cid="+cid;
			// 创建WebSocket实例，下面那个MozWebSocket是Firefox的实现
			if ('WebSocket' in window) { 
				ws = new WebSocket(url);
			} else if ('MozWebSocket' in window) { 
				ws = new MozWebSocket(url); 
			} else { 
				alert('Unsupported.'); 
				return; 
			}

			// WebSocket握手完成，连接成功的回调
			// 有个疑问，按理说new WebSocket的时候就会开始连接了，如果在设置onopen以前连接成功，是否还会触发这个回调
			ws.onopen = function() { 
				$('#msg').append('Opened!<br />')
	        };

	        // 收到服务器发送的文本消息, event.data表示文本内容
			ws.onmessage = function(event) { 
				$('#msg').append('Receive message: ' + event.data+'<br />')
			};

			// 关闭WebSocket的回调
			ws.onclose = function() {
				$('#msg').append('Closed!<br />')
			};
		}

		function sendMyMessage() {
			var textMessage = document.getElementById('textMessage').value;
			
			if(ws != null && textMessage != '') {
				// 通过WebSocket想向服务器发送一个文本信息
					var json = '{"t":1,"id":"0","m":"'+textMessage+'"}';
					ws.send(json);
			}
		}
		</script>
</head>
<body>
	UID:<input type="text" id="uid" size="20" /><br />
	CID:<input type="text" id="cid" size="20" /><br />
	<input type="text" id="textMessage" size="20" />
	<input type="button" onclick="startServer()" value="connect">
	<input type="button" onclick="sendMyMessage()" value="Send">
	<div id="msg" style="width: 500px;height: 500px;"></div>
</body>
</html>
